Web development and Tech news Blog site. WEBISFREE.com

HOME > linux

[Linux] Exploring How to Find and Replace File Text

Last Modified : 29 Aug, 2023 / Created : 29 Aug, 2023
512
View Count
There are times in Linux when you want to find a specific file and change its content. For instance, if you want to find the text "vue" in the language.json file and replace it with "nuxt", how should you do it?

@ language.txt
{
  "framework": "vue"
}

// We aim to change the "vue" text as follows:
{
  "framework": "nuxt"
}
Several methods exist to change the content of a file. Below, we will try to replace specific text with another text in Linux using the sed command. We will also explore the use of regular expressions.



# Changing File Content in Linux with sed


sed helps to find a particular phrase in a file and change it. Its basic syntax is as follows:

sed option 's/targetText/replaceText/' targetFile

After sed, there's an option, and next, you can enter text separated by the / symbol. Each keyword is used as follows:

option // [Optional] Used when setting options
s // Finds and replaces text
targetText // The text to target
replaceText // The text that will replace the target
targetFile // The name of the target file

Now, let's explore how to use it with a simple example.


! Examples of changing text with sed


We will create several examples and look at each case, including the standard case and the one using regular expressions.

Replacing "apple" with "orange"
To replace "apple" with "orange" in the file.txt:
sed 's/apple/orange/' file.txt

This is the simplest method.


Replacing all instances of "apple" with "orange"
The example above changes only one instance of the text. To change all instances, add a 'g' after the text to be replaced.
sed 's/apple/orange/g' file.txt

Now, all "apple" are changed to "orange".


Using the -i flag option for file modification
Without using the -i, the file is not saved but only printed. To actually change and save the file, use the -i flag.
sed -i 's/apple/orange/g' file.txt

Changes are displayed, and you can see that the file is modified.


Using regular expressions to replace either "apple" or "banana" with "orange"
Regular expressions are basically used, but to apply all recent regular expressions, the -E option is necessary. For example, to use symbols like '+' or '|', you need to add the -E option as follows:
sed -E 's/apple|banana/orange/g' file.txt

Now, using the pipeline symbol, it's possible to find and replace either "apple" or "banana".


We've briefly looked at ways to change file content and text in Linux.
Perhaps you're looking for the following text as well?

    Previous

    Learn about the Linux command rename

    Previous

    Issue Fix: Unable to Use Wide Monitor Resolution with Ubuntu 22